package sumNumbers;

import java.util.ArrayDeque;

public class CalculatingParser {
    public static void main(String[] args) {
        bracketHandler("(1+1+2)");
    }
    private static int testTryCatch(){
        try {
            int i = 1/0;
            return 3 ;
        }catch (Exception e){
            e.printStackTrace();
            return 1 ;
        }finally {
            return 0;
        }
    }

    private static void bracketHandler(String input){
        ArrayDeque<String> ad = new ArrayDeque<>();
        String cal = "" ;
        char[] chars = input.toCharArray();
        for(char aChar : chars){
            if(")".equals(""+aChar)){
                String s = ad.pollLast();
                while(!"(".equals(s)){
                    cal = s + cal ;
                    s = ad.pollLast();
                }
                ad.pollLast();
                int calculate = calculate(cal);
                ad.add(""+calculate);
            }else{
                ad.add(""+aChar);
            }
        }
        System.out.println(ad.pollLast());
    }
    private static boolean contains(String cnt , String target){
       return cnt.contains(target);
    }
    private static int calculate(String calculation){
        char[] chars = calculation.toCharArray();
        int rs = 0 ;
        String temp = "" ;
        char operator = '+' ;
        for(char aChar : chars){
            if(!contains("+-" , ""+aChar)){
                temp += aChar ;
            }else{
                if('-' == operator){
                    rs -= Integer.parseInt(temp);
                }else if('+' == operator){
                    rs += Integer.parseInt(temp);
                }
                operator = aChar ;
                temp = "" ;
            }

        }
        if('-' == operator){
            rs -= Integer.parseInt(temp);
        }else if('+' == operator){
            rs += Integer.parseInt(temp);
        }
        return rs ;
    }
}
